Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Make Array Zero by Subtracting Equal Amounts

Problem Statement

Given an array of positive integers nums, return the minimum number of operations required to make all elements of nums 0.

In one operation, you must:

  • Select a positive integer n such that n is less than or equal to the smallest positive element in nums.
  • Subtract n from every non-zero element in nums.

Examples

  • Example 1:

    • Input: nums = [3,3,2]
    • Expected Output: 2
    • Justification: Subtract 2 from all non-zero elements to get [1,1,0]. Then, subtract 1 to get all zeros. 2 steps are required.
  • Example 2:

    • Input: [1,2,3,4,5]
    • Expected Output: 5
    • Justification: Since all elements are unique, each step involves subtracting 1 from a unique non-zero element, requiring 5 steps to turn the array into zeros.
  • Example 3:

    • Input: [4,4,4,3,3,2,2,1]
    • Expected Output: 4
    • Justification: After removing duplicates, we have [4,3,2,1]. Each number represents a unique subtraction step, hence 4 steps are needed.

Solution

To solve this problem, the most effective strategy is to focus on the unique non-zero elements in the array. Since subtracting the same amount from different numbers doesn't depend on the numbers being consecutive or related, we can essentially "ignore" the operation's effect on the array's structure and simply count how many unique operations we can perform. This approach is efficient because it directly correlates the number of steps to the number of unique non-zero values in the array, bypassing the need to simulate each subtraction operation.

First, we filter out all zeros from the array since they do not affect the operation count. Then, by converting the remaining numbers to a set, we eliminate duplicates, leaving us with the unique non-zero values. The size of this set directly gives us the answer: it represents the minimum number of distinct subtraction operations needed to reduce every element to zero. This method is straightforward and avoids unnecessary computations, making it an optimal solution for the problem.

Step-by-step Algorithm

  1. Initialize a Set: Start by creating an empty set. This set will be used to store the unique non-zero elements found in the input array. The use of a set ensures that each element is counted only once, regardless of how many times it appears in the array.

  2. Iterate Over the Array: Loop through each element in the input array. For each element, check if it is greater than zero. We are only interested in non-zero elements because zeros do not affect our operation count.

  3. Add Non-Zero Elements to the Set: If an element is greater than zero, add it to the set created in step 1. Since sets automatically handle duplicates, any repeated non-zero value will not affect the size of the set.

  4. Calculate the Size of the Set: After all non-zero elements have been added to the set, the size of the set represents the number of unique non-zero values in the original array. This size directly corresponds to the minimum number of steps required to reduce all elements to zero.

  5. Return the Size of the Set: The final step of the algorithm is to return the size of the set as the answer. This value indicates the minimum number of subtraction operations needed to turn the array into all zeros.

Algorithm Walkthrough

Given the input [4,4,4,3,3,2,2,1], let's walk through the algorithm:

  1. Initialize a Set: Create an empty set to store unique non-zero values.

  2. Iterate Over the Array:

    • First element, 4: It's greater than zero, so add it to the set.
    • Second element, 4: Already exists in the set, so it's ignored.
    • Third element, 4: Same as above, ignored.
    • Fourth element, 3: It's greater than zero and not in the set, so add it.
    • Fifth element, 3: Already exists in the set, so it's ignored.
    • Sixth element, 2: It's greater than zero and not in the set, so add it.
    • Seventh element, 2: Already exists in the set, so it's ignored.
    • Eighth element, 1: It's greater than zero and not in the set, so add it.
  3. Add Non-Zero Elements to the Set: After iterating through the array, the set contains the elements {1, 2, 3, 4}.

  4. Calculate the Size of the Set: The set size is 4, representing the four unique non-zero values in the array.

  5. Return the Size of the Set: Return 4 as the minimum number of steps required to reduce the array to zeros.

Image

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The primary operation in the algorithm is iterating through the input array once, leading to an overall time complexity, where N is the number of elements in the array.

Space Complexity

The extra space is used to store unique non-zero elements in a set or map. In the worst case, if all elements are unique and non-zero, the space complexity would be . However, since we're focusing on the unique non-zero elements, it's more precise to denote it as .

Make Array Zero by Subtracting Equal Amounts (easy)
Leaf-Similar Trees (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity